package com.young.dubbo.protocol.http;

import com.young.dubbo.framework.Invocation;
import com.young.dubbo.provider.LocalRegister;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 处理请求
 */
public class HttpServerHandler {
    private Logger logger = LoggerFactory.getLogger(HttpServerHandler.class);

    public void handler(HttpServletRequest request, HttpServletResponse httpServletResponse){
        try {
            // 获取请求输入流，并转成对应的对象流
            ServletInputStream inputStream = request.getInputStream();
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);

            // 读取对应的参数信息
            Invocation invocation = (Invocation)objectInputStream.readObject();
            String interfaceName = invocation.getInterfaceName();

            // 从注册中心获取接口的Class对象
            Class implClass = LocalRegister.get(interfaceName);

            //调用对应的方法
            Method method = implClass.getMethod(invocation.getMethodName(), invocation.getParamTypes());
            String result = (String)method.invoke(implClass.newInstance(), invocation.getParams());
            logger.info("tomcat:{}",result);
            // 写出到响应流
            IOUtils.write(result,httpServletResponse.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }
}
